<template>
  <!-- 写日记的新建标签没有完成 -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="50px"
    >
      <el-form-item label="内容" prop="contentPreview">
        <el-input
          v-model="queryParams.contentPreview"
          placeholder="请输入日记内容"
          clearable
          @keyup.enter="handleQuery"
          style="width: 180px;"
        />
      </el-form-item>
      <el-form-item label="日期" prop="date">
        <el-date-picker
          clearable
          v-model="queryParams.date"
          type="daterange"
          value-format="YYYY-MM-DD"
          unlink-panels
          placeholder="请选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
          size="default"
          style="width: 250px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入地点"
          clearable
          @keyup.enter="handleQuery"
          style="width: 180px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['diary:diary:add']"
        >写日记</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['diary:diary:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['diary:diary:export']"
        >导出</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-select
          v-model="queryParams.mood"
          filterable
          clearable
          placeholder="心情"
          @change="(selectedId)=>handleChange(selectedId,1,1)"
          @clear="()=>resetSvgCode(1,1)"
          style="width: 100px;"
          class="no-border-select"
        >
          <template #prefix>
            <div v-html="modifySvgSize(index_moodSvgCode,2)" class="query-svg-icon"></div>
          </template>
          <el-option
            v-for="mood in moodTags"
            :key="mood.id"
            :label="mood.labelName"
            :value="mood.id"
          >
            <i
              v-html="modifySvgSize(mood.svgCode,2)"
              style="margin-right: 10px; margin-top:5px; display: inline-block; vertical-align: middle;"
            ></i>
            {{ mood.labelName }}
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="1.5" style="margin-left: -10px;">
        <el-select
          v-model="queryParams.weather"
          filterable
          clearable
          placeholder="天气"
          @change="(selectedId)=>handleChange(selectedId,0,1)"
          @clear="()=>resetSvgCode(0,1)"
          style="width: 100px;"
          class="no-border-select"
        >
          <template #prefix>
            <div v-html="modifySvgSize(index_weatherSvgCode,2)" class="query-svg-icon"></div>
          </template>
          <el-option
            v-for="weather in weatherTags"
            :key="weather.id"
            :label="weather.labelName"
            :value="weather.id"
          >
            <i
              v-html="modifySvgSize(weather.svgCode,2)"
              style="margin-right: 10px; margin-top:5px; display: inline-block; vertical-align: middle;"
            ></i>
            {{ weather.labelName }}
          </el-option>
        </el-select>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 写日记对话框 -->
    <el-dialog v-model="showDialog" width="850px" append-to-body>
      <!-- <el-form ref="diaryRef" :model="form" :rules="rules"> -->
      <el-form :model="form" :rules="rules">
        <div style="margin-top: -40px;">
          <el-input
            v-model="form.title"
            class="title-input"
            placeholder="写下今天的标题..."
            :disabled="!isEdit"
          ></el-input>

          <div class="info-row">
            <div class="auto-area">
              <div>{{ form.dateDisplay }}</div>

              <div class="location">
                <i v-html="blueLocation" style="margin-top: 4px;"></i>
                <el-tooltip v-if="form.location" :content="form.location" placement="top">
                  <span
                    style="display: inline-block; width:150px;margin-left:5px"
                    class="text-overflow-ellipsis"
                  >{{ form.location }}</span>
                </el-tooltip>
                <el-tooltip v-else content="正在加载中..." placement="top">
                  <el-icon style="margin-left:5px" class="is-loading">
                    <Loading />
                  </el-icon>
                </el-tooltip>
              </div>
            </div>

            <div class="function-area">
              <div class="mood">
                <el-select
                  v-model="form.mood"
                  clearable
                  placeholder="心情"
                  @change="(selectedId)=>handleChange(selectedId,1,0)"
                  @clear="()=>resetSvgCode(1,0)"
                  style="width: 100px;"
                  class="no-border-select"
                  :disabled="!isEdit"
                >
                  <template #prefix>
                    <div v-html="modifySvgSize(dialog_moodSvgCode,2)" class="write-svg-icon"></div>
                  </template>
                  <el-option
                    v-for="mood in moodTags"
                    :key="mood.id"
                    :label="mood.labelName"
                    :value="mood.id"
                  >
                    <i
                      v-html="modifySvgSize(mood.svgCode,2)"
                      style="margin-right: 10px; margin-top:5px; display: inline-block; vertical-align: middle;"
                    ></i>
                    {{ mood.labelName }}
                  </el-option>
                </el-select>
              </div>

              <div class="weather">
                <el-select
                  v-model="form.weather"
                  clearable
                  placeholder="天气"
                  @change="(selectedId)=>handleChange(selectedId,0,0)"
                  @clear="()=>resetSvgCode(0,0)"
                  style="width: 100px;"
                  class="no-border-select"
                  :disabled="!isEdit"
                >
                  <template #prefix>
                    <div v-html="modifySvgSize(dialog_weatherSvgCode,2)" class="write-svg-icon"></div>
                  </template>
                  <el-option
                    v-for="weather in weatherTags"
                    :key="weather.id"
                    :label="weather.labelName"
                    :value="weather.id"
                  >
                    <i
                      v-html="modifySvgSize(weather.svgCode,2)"
                      style="margin-right: 10px; margin-top:5px; display: inline-block; vertical-align: middle;"
                    ></i>
                    {{ weather.labelName }}
                  </el-option>
                </el-select>
              </div>

              <div class="tags">
                <el-popover placement="bottom" :width="140" trigger="click" :disabled="!isEdit">
                  <template #reference>
                    <el-tag
                      v-if="selectedTag"
                      :style="{ 
                        backgroundColor: lightenColor(selectedTag.color, 0.1), 
                        color: selectedTag.color, 
                        borderColor: lightenColor(selectedTag.color, 0.3), 
                        padding: '4px 10px',
                        '--tag-close-color': selectedTag.color,
                        cursor : isEdit ? 'default' : 'not-allowed'
                        }"
                      effect="light"
                      round
                      :closable="isEdit"
                      @close="resetTag"
                      style="margin-right: 0px; width: 114px; margin-left: 10px"
                    >{{ selectedTag && selectedTag.labelName ? (selectedTag.labelName.length >= 6 ? selectedTag.labelName.slice(0, 6) : selectedTag.labelName) : '' }}</el-tag>
                    <el-tag
                      v-else
                      effect="light"
                      round
                      style="margin-right: 0px; width:114px; margin-left: 10px"
                      :style="{cursor : isEdit ? 'default' : 'not-allowed'}"
                    >无标签</el-tag>
                  </template>
                  <div
                    style="display: flex; flex-direction: column;max-height: 250px; overflow-y: auto;"
                  >
                    <el-tag
                      v-for="tag in categoryTags"
                      :key="tag.id"
                      :style="{ backgroundColor: lightenColor(tag.color, 0.1), color: tag.color, borderColor: lightenColor(tag.color, 0.3), padding: '4px 10px', margin: '5px 0' }"
                      effect="plain"
                      round
                      @click="selectTag(tag)"
                      style="cursor: pointer;"
                    >{{ tag.labelName }}</el-tag>
                    <el-tag
                      :style="{ backgroundColor: '#f0f9eb', color: '#67c23a', borderColor: '#e1f3d8', padding: '4px 10px', margin: '5px 0' }"
                      effect="plain"
                      round
                      @click="showNewTagForm"
                      style="cursor: pointer;"
                    >+ 新建标签</el-tag>
                  </div>
                </el-popover>
              </div>
            </div>
          </div>

          <div class="text-editor-area">
            <textEditor
              v-model="form.contentPreview"
              :height="showMedia ? 350 : 516"
              @update:wordCount="updateWordCount"
              :isDisabled="!isEdit"
            />
            <div class="icon-word-count">
              <div class="icon-container">
                <el-link
                  :icon="showMedia ? ArrowUpBold : ArrowDownBold"
                  @click="toggleMediaUpload"
                  :underline="false"
                  class="up-down-arrow"
                ></el-link>
              </div>
              <div class="word-count">
                {{ form.wordCount }}
                <span>字</span>
              </div>
            </div>
          </div>

          <div class="image-upload-area" v-if="showMedia">
            <span class="image-upload-title">已上传的图片文件</span>
            <imageUpload class="image-upload" v-model="form.attachUrl" :isDisabled="!isEdit" />
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-switch
            v-if="isViewOrEdit"
            v-model="isEdit"
            class="mb-2"
            size="small"
            active-text="编辑"
            inactive-text="查看"
            style="margin-right:275px"
          />
          <el-link :icon="CloseBold" @click="cancel" :underline="false">取消</el-link>
          <el-link
            :icon="Select"
            @click="submitForm"
            :underline="false"
            style="margin-left: 10px;"
            :disabled="!isEdit"
          >保存</el-link>
        </div>
      </template>
    </el-dialog>

    <el-table v-loading="loading" :data="diaryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="date" width="100" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="心情" align="center" prop="mood" width="55">
        <template #default="scope">
          <el-tooltip :content="scope.row.moodLabelName" placement="top">
            <div v-html="modifySvgSize(scope.row.moodSvgCode,2) || '无图标'"></div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" width="150" prop="title" show-overflow-tooltip />
      <el-table-column label="内容预览" align="center" prop="contentPreview">
        <template #default="scope">
          <el-popover
            placement="top"
            :width="650"
            trigger="click"
            :content="scope.row.newContentPreview"
          >
            <template #reference>
              <div class="text-overflow-ellipsis">{{ scope.row.newContentPreview }}</div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="字数" align="center" prop="wordCount" width="80" sortable />
      <el-table-column label="地点" align="center" prop="location" show-overflow-tooltip width="180" />
      <el-table-column label="天气" align="center" prop="weather" width="55">
        <template #default="scope">
          <el-tooltip :content="scope.row.weatherLabelName" placement="top">
            <div v-html="modifySvgSize(scope.row.weatherSvgCode,0) || '无图标'"></div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="标签"
        align="center"
        prop="categoryId"
        width="150"
        :filters="categoryTagList"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template #default="scope">
          <el-tag
            v-if="scope.row.categoryLabelName"
            :style="{ backgroundColor: lightenColor(scope.row.categoryColor,0.1), color: scope.row.categoryColor, borderColor: lightenColor(scope.row.categoryColor,0.3), padding: '4px 10px', }"
            effect="light"
            round
          >{{ scope.row.categoryLabelName.length >= 6 ? scope.row.categoryLabelName.slice(0, 6) : scope.row.categoryLabelName }}</el-tag>
          <el-tag v-else effect="light" round type="danger">无标签</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['diary:diary:edit']"
          >查看</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['diary:diary:remove']"
          >更多</el-button>-->
          <el-tooltip content="查看" placement="top">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              style="margin-right: 5px;"
            ></el-button>
          </el-tooltip>

          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>

          <!-- <el-button link type="primary" icon="More" @click="handleMore(scope.row)"></el-button> -->
          <!-- <el-dropdown trigger="click" @command="(command) => handleCommand(command, scope.row)">
            <span class="dropdown-link">
              <el-tooltip content="更多" placement="top">
                <el-button link type="primary" icon="More"></el-button>
              </el-tooltip>
            </span>

            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit" icon="Edit">编辑</el-dropdown-item>
                <el-dropdown-item command="detail" icon="Reading">详情</el-dropdown-item>
                <el-dropdown-item command="attachment" icon="Paperclip">附件</el-dropdown-item>
                <el-dropdown-item command="export" icon="Download">导出</el-dropdown-item>
                <el-dropdown-item command="delete" icon="Delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 小宠物 -->
    <pet :bubbleText="feedback" :showBubble="showBubble" />
  </div>
</template>

<script setup name="Diary">
import {
  listDiary,
  getDiary,
  delDiary,
  addDiary,
  updateDiary
} from "@/api/diary/diary";
import { listCategoryTag } from "@/api/categoryTag/categoryTag";
import { listMoodWeather } from "@/api/moodWeather/moodWeather";
import textEditor from "@/components/Editor/indexOptimized.vue";
import imageUpload from "@/components/ImageUpload/indexOptimized.vue";
import pet from "@/views/components/PetEmotionFeedback.vue";
import { petChat } from "@/api/zhipuAI/zhipuAI";
import { ref } from "vue";
import {
  ArrowDownBold,
  ArrowUpBold,
  CloseBold,
  Select,
  Loading
} from "@element-plus/icons-vue";
import axios from "axios";

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    date: null,
    startDate: null,
    endDate: null,
    mood: null,
    contentPreview: null,
    location: null,
    weather: null,
    categoryId: null
  },
  form: {},
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);

const showSearch = ref(true);
const isViewOrEdit = ref(false);
const isEdit = ref(false);
const dialogDisable = ref(false);
const showMedia = ref(false);
const showDialog = ref(false);
const selectedTag = ref(null);

const { proxy } = getCurrentInstance();

const diaryList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const open = ref(false);
// 保存日记后AI的反馈
const feedback = ref("");
const showBubble = ref(false);

// 心情天气标签数组
const weatherTags = ref([]);
const moodTags = ref([]);
const categoryTagList = ref([]);
const categoryTags = ref([]);
// svg代码
const initialMoodSvgCode =
  '<svg t="1738335269784" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1700" width="22" height="22"><path d="M756.364 465.455a58.182 58.182 0 1 1 0-116.364 58.182 58.182 0 0 1 0 116.364M512 791.273A151.459 151.459 0 0 1 360.727 640a34.91 34.91 0 0 1 69.818 0c0 44.916 36.539 81.455 81.455 81.455s81.455-36.539 81.455-81.455a34.91 34.91 0 0 1 69.818 0c0 83.41-67.864 151.273-151.273 151.273M279.273 465.455a58.182 58.182 0 1 1 0-116.364 58.182 58.182 0 0 1 0 116.364M512 23.273C242.083 23.273 23.273 242.083 23.273 512S242.083 1000.727 512 1000.727 1000.727 781.917 1000.727 512 781.917 23.273 512 23.273" fill="#1890ff" p-id="1701"></path></svg>';
const index_moodSvgCode = ref(initialMoodSvgCode);
const dialog_moodSvgCode = ref(initialMoodSvgCode);
const initialWeatherSvgCode =
  '<svg t="1738340954666" class="icon" viewBox="0 0 1035 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1542" data-spm-anchor-id="a313x.manage_type_mylikes.0.i2.48b33a81j7O2eb" width="200" height="200"><path d="M921.348011 358.302004h102.372002v102.372002h-102.372002zM563.046007 0h102.372001v102.372001h-102.372001zM795.328078 156.168488l72.377005-72.377005 72.377005 72.377005-72.377005 72.377005zM288.586672 156.219674l72.377004-72.428191 72.377005 72.428191-72.377005 72.377005z" fill="#1890ff" p-id="1543" data-spm-anchor-id="a313x.manage_type_mylikes.0.i1.48b33a81j7O2eb" class="selected"></path><path d="M815.90485 563.046007A251.835123 251.835123 0 0 0 870.162011 409.488005a255.930003 255.930003 0 0 0-255.930003-255.930003 255.930003 255.930003 0 0 0-232.896303 153.558002H358.302004a358.302004 358.302004 0 0 0 0 716.604009h435.081006a229.825143 229.825143 0 0 0 22.52184-460.674006z m-22.52184 358.302004H358.302004a255.930003 255.930003 0 1 1 251.835123-298.414383l7.166041 42.48438h176.079842a127.965002 127.965002 0 0 1 0 255.930003z" fill="#1890ff" p-id="1544" data-spm-anchor-id="a313x.manage_type_mylikes.0.i0.48b33a81j7O2eb" class="selected"></path></svg>';
const index_weatherSvgCode = ref(initialWeatherSvgCode);
const dialog_weatherSvgCode = ref(initialWeatherSvgCode);
const blueLocation = ref(
  '<svg t="1738334523196" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1542" width="18" height="18"><path d="M512 64C335.296 64 192 208.064 192 385.728S512 960 512 960s320-396.544 320-574.272S688.704 64 512 64z m0 461.184c-70.72 0-128-57.6-128-128.704 0-71.104 57.28-128.704 128-128.704s128 57.6 128 128.704c0 71.04-57.28 128.704-128 128.704z" fill="#1890FF" p-id="1543"></path></svg>'
);

const shortcuts = [
  {
    text: "Last week",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "Last month",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "Last 3 months",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];

onMounted(() => {
  getCurrentDateTime();
});

// 初始化页面，数据

/** 查询日记管理列表 */
// function getList() {
//   loading.value = true;
//   diaryList.value = [];
//   listDiary({
//     ...queryParams.value,
//     date: undefined
//   })
//     .then(response => {
//       diaryList.value = response.rows;
//       total.value = response.total;
//       loading.value = false;
//     })
//     .catch(error => {
//       console.error("Error fetching data:", error);
//       loading.value = false;
//     });
// }
function getList() {
  loading.value = true;
  diaryList.value = [];
  listDiary({
    ...queryParams.value,
    date: undefined
  })
    .then(response => {
      diaryList.value = response.rows.map(row => {
        const contentPreview = row.contentPreview;
        const newContentPreview = contentPreview
          ? extractPlainText(contentPreview)
          : contentPreview;
        return {
          ...row,
          newContentPreview
        };
      });
      total.value = response.total;
      loading.value = false;
      console.log(diaryList.value);
    })
    .catch(error => {
      console.error("Error fetching data:", error);
      loading.value = false;
    });
}
/** 查询所有新建标签列表 */
function getAllCategoryTagList() {
  loading.value = true;
  listCategoryTag({
    pageNum: 1,
    pageSize: 1000
  })
    .then(response => {
      loading.value = false;
      categoryTags.value = response.rows;
      // categoryTagList用于标签一列的过滤
      categoryTagList.value = response.rows.map(row => ({
        text: row.labelName,
        value: row.labelName
      }));
      return categoryTagList.value;
    })
    .catch(error => {
      console.error("获取新建标签列表失败:", error);
      loading.value = false;
      return [];
    });
}
/** 查询所有心情天气标签列表 */
function getAllMoodWeatherList() {
  loading.value = true;
  listMoodWeather({
    pageNum: 1,
    pageSize: 1000
  })
    .then(response => {
      weatherTags.value = response.rows.filter(row => row.isMood === 0);
      moodTags.value = response.rows.filter(row => row.isMood === 1);
      console.log("获取心情天气标签列表成功:", weatherTags.value);
      loading.value = false;
    })
    .catch(error => {
      console.error("获取心情天气标签列表失败:", error);
      loading.value = false;
    });
}

// 功能按钮

/** 搜索按钮操作 */
function handleQuery() {
  if (queryParams.value.date && queryParams.value.date.length === 2) {
    queryParams.value.startDate = queryParams.value.date[0];
    queryParams.value.endDate = queryParams.value.date[1];
  } else {
    queryParams.value.startDate = null;
    queryParams.value.endDate = null;
  }
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.mood = null;
  resetSvgCode(1, 1);
  queryParams.value.weather = null;
  resetSvgCode(0, 1);
  handleQuery();
}
/** 写日记按钮操作 */
function handleAdd() {
  reset();
  showMedia.value = false;
  getCurrentDateTime();
  isViewOrEdit.value = false;
  isEdit.value = true;
  showDialog.value = true;

  // 检查浏览器是否支持地理定位 API
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      position => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        // 使用经纬度获取详细地址
        getAddressFromCoordinates(latitude, longitude);
      },
      error => {
        console.error("获取位置失败:", error);
        form.value.location = "无法获取位置";
      },
      {
        enableHighAccuracy: true, // 提高精度
        timeout: 5000, // 设置超时时间
        maximumAge: 0 // 不使用缓存位置
      }
    );
  } else {
    console.error("浏览器不支持地理定位 API");
    form.value.location = "浏览器不支持地理定位";
  }
}
/** 写日记---下或上拉按钮操作 */
function toggleMediaUpload() {
  showMedia.value = !showMedia.value;
}
/** 写日记---保存按钮操作 */
function submitForm() {
  const { title, date, location, mood, weather, contentPreview } = form.value;

  // 验证逻辑
  if (!title) {
    proxy.$notify.warning({
      title: "标题",
      message: "别忘了，标题是日记的小眼睛呢~"
    });
    return;
  }
  if (!date) {
    proxy.$notify.warning({
      title: "时间",
      message: "别让时间悄悄溜走，快在日记里留下它的足迹！"
    });
    return;
  }
  if (!location) {
    proxy.$notify.warning({
      title: "地点",
      message: "别让日记里的故事四处漂泊哦~"
    });
    return;
  }
  if (!mood) {
    proxy.$notify.warning({
      title: "心情",
      message: "心情小角落还空着呢，快来填满它吧！"
    });
    return;
  }
  if (!weather) {
    proxy.$notify.warning({
      title: "天气",
      message: "天气变化万千，记得在日记里捕捉这一天的天空！"
    });
    return;
  }
  if (!contentPreview) {
    proxy.$notify.warning({
      title: "内容",
      message: "日记里还差你的故事，快来填补空白吧!"
    });
    return;
  }
  // console.log("form.value.id:", form.value.id);

  // 获取 moodLabelName
  const selectedMood = moodTags.value.find(moodTag => moodTag.id === mood);
  const moodLabelName = selectedMood ? selectedMood.labelName : "";

  // 获取 newContentPreview
  const newContentPreview = extractPlainText(contentPreview);

  // 构建请求参数
  const requestData = {
    content: newContentPreview,
    emotion: moodLabelName,
    isDiaryProcessing: true
  };

  // 调用AI接口
  petChat(requestData, partialText => {
    feedback.value = partialText; //实时更新
    showBubble.value = true;
  })
    .then(finalText => {
      console.log("最终内容：", finalText);
      setTimeout(() => (showBubble.value = false), 6000); //传输完成6s后关闭对话框
    })
    .catch(error => {
      console.error("获取AI反馈失败:", error);
      if (error.message.include("超时")) {
        showTimeoutAlert(); //显示超时提示
      }
    });

  // 新增或修改
  if (form.value.id != null) {
    updateDiary(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      showDialog.value = false;
      getList();
    });
  } else {
    addDiary(form.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      showDialog.value = false;
      getList();
    });
  }
}
/** 写日记---取消按钮操作 */
function cancel() {
  showDialog.value = false;
  reset();
}
/** 写日记---新建标签操作 */
function showNewTagForm() {
  console.log("显示新建标签表单");
}
/** 表格---查看按钮操作 */
function handleView(row) {
  reset();
  const _id = row.id;
  isEdit.value = false;
  isViewOrEdit.value = true;
  getDiary(_id).then(response => {
    form.value = response.data;
    const dateStr = form.value.date;
    const date = new Date(dateStr);
    form.value.dateDisplay = dateFormatConversion(date);
    dialog_moodSvgCode.value = form.value.moodSvgCode; //处理心情图标
    dialog_weatherSvgCode.value = form.value.weatherSvgCode; //处理天气图标
    // 处理标签图标
    if (form.value.categoryId) {
      selectedTag.value = {
        id: form.value.categoryId,
        color: form.value.categoryColor,
        labelName: form.value.categoryLabelName
      };
    } else {
      selectedTag.value = null;
    }
    isEdit.value = false;
    showMedia.value = form.value.attachUrl ? true : false;
    showDialog.value = true;
  });
}
/** 表格---删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm("删除日记将一并删除关联图片，是否确认？")
    .then(function() {
      return delDiary(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

// 功能函数
/**
 * 提取 HTML 中的纯文本
 * @param html - HTML 字符串
 */
function extractPlainText(html) {
  if (html && /<[^>]+>/g.test(html)) {
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = html;
    return tempDiv.textContent || "";
  } else {
    return html;
  }
}
/** 修改svg图标大小：修改 svgCode 代码中的 width 和 height 属性
 * @param {string} svgCode - 要修改的 SVG 代码
 * @param {number} sizeTag - 0：22px，1：30px，2：18px
 * @returns {string} - 修改后的 SVG 代码
 */
function modifySvgSize(svgCode, sizeTag) {
  if (svgCode) {
    const parser = new DOMParser();
    const svgDoc = parser.parseFromString(svgCode, "image/svg+xml");
    const svgElement = svgDoc.querySelector("svg");
    if (svgElement) {
      if (sizeTag === 0) {
        svgElement.setAttribute("width", "22");
        svgElement.setAttribute("height", "22");
      } else if (sizeTag === 1) {
        svgElement.setAttribute("width", "30");
        svgElement.setAttribute("height", "30");
      } else if (sizeTag === 2) {
        svgElement.setAttribute("width", "18");
        svgElement.setAttribute("height", "18");
      }
      return new XMLSerializer().serializeToString(svgElement);
    }
  }
  return svgCode;
}
/** 获取当前时间并格式化 */
function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  const dayOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][
    now.getDay()
  ];
  // 前端显示格式
  form.value.dateDisplay = `${year}年${month}月${day}日 ${hours}:${minutes} ${dayOfWeek}`;
  // 后端传递格式
  form.value.date = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
/** 格式化后端返回的日期 */
function dateFormatConversion(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const dayOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][
    date.getDay()
  ];
  const dateDisplay = `${year}年${month}月${day}日 ${hours}:${minutes} ${dayOfWeek}`;
  return dateDisplay;
}
/** 日记重置 */
function reset() {
  form.value = {
    id: null,
    userId: null,
    date: null,
    dateDisplay: null,
    mood: null,
    title: null,
    contentPreview: null,
    wordCount: 0,
    location: null,
    weather: null,
    categoryId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  form.value.contentPreview = undefined;
  resetSvgCode(1, 0); //重置心情图标
  resetSvgCode(0, 0); //重置天气图标
  resetTag(); //重置标签图标
  // proxy.resetForm("diaryRef");
}
/** 心情天气svgCode图标重置
 * @param {number} moodFlag - 标签类型，1代表心情，0代表天气
 * @param {number} isIndex - 当前页面类型，1代表index页面即首页，0代表dialog页面即写日记页面
 */
function resetSvgCode(moodFlag, isIndex) {
  if (moodFlag === 1) {
    if (isIndex === 1) {
      index_moodSvgCode.value = initialMoodSvgCode;
    } else if (isIndex === 0) {
      dialog_moodSvgCode.value = initialMoodSvgCode;
    }
  } else if (moodFlag === 0) {
    if (isIndex === 1) {
      index_weatherSvgCode.value = initialWeatherSvgCode;
    } else if (isIndex === 0) {
      dialog_weatherSvgCode.value = initialWeatherSvgCode;
    }
  }
}
/** 标签图标重置 */
function resetTag() {
  selectedTag.value = null;
}
/** 拿到所选标签的svgCode，调用函数更新
 * @param {number} selectedId - 选中的标签的ID
 * @param {number} moodFlag - 标签类型，1代表心情，0代表天气
 * @param {number} isIndex - 当前页面类型，1代表index页面即首页，0代表dialog页面即写日记页面
 */
function handleChange(selectedId, moodFlag, isIndex) {
  console.log("selectedId=" + selectedId);
  if (moodFlag === 1) {
    const selectedMood = moodTags.value.find(mood => mood.id === selectedId);
    if (selectedMood) {
      updateSvgCode(selectedMood.svgCode, 1, isIndex);
    }
  } else if (moodFlag === 0) {
    const selectedWeather = weatherTags.value.find(
      weather => weather.id === selectedId
    );
    if (selectedWeather) {
      updateSvgCode(selectedWeather.svgCode, 0, isIndex);
    }
  }
}
/** 动态更新svgCode
 * @param {string} newSvg - 新的svgCode
 * @param {number} moodFlag - 标签类型，1代表心情，0代表天气
 * @param {number} isIndex - 当前页面类型，1代表index页面即首页，0代表dialog页面即写日记页面
 */
function updateSvgCode(newSvg, moodFlag, isIndex) {
  if (moodFlag === 1) {
    if (isIndex === 1) {
      index_moodSvgCode.value = newSvg;
    } else if (isIndex === 0) {
      dialog_moodSvgCode.value = newSvg;
    }
  } else if (moodFlag === 0) {
    if (isIndex === 1) {
      index_weatherSvgCode.value = newSvg;
    } else if (isIndex === 0) {
      dialog_weatherSvgCode.value = newSvg;
    }
  }
}
/** 写日记字数统计 */
function updateWordCount(newVal) {
  form.value.wordCount = newVal;
  console.log("wordCount.value=" + form.value.wordCount);
}
/**  根据经纬度获取当前地理位置的详细信息
 * @param {number} latitude - 纬度
 * @param {number} longitude - 经度
 */
function getAddressFromCoordinates(latitude, longitude) {
  const amapKey = "ab44a5721b143628beed1b479d0b0465"; // 高德地图 API Key
  const url = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${amapKey}`;

  axios
    .get(url)
    .then(response => {
      // console.log(response.data);
      console.log(response.data.regeocode);
      // 详细地址
      const detailAddress = response.data.regeocode.formatted_address;
      // 简洁地址 simpleAddress
      form.value.location = detailAddress;
    })
    .catch(error => {
      console.error("获取地址失败:", error);
      form.value.location = "无法获取地址";
    });
}
/** rgb转为rgba，即增加透明度 */
function lightenColor(hex, alpha) {
  const rgb = hexToRgb(hex);
  if (rgb) {
    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
  }
  return hex;
}
/** 将颜色的十六进制格式转为rbg格式 */
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      }
    : null;
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 表格标签列过滤 */
const filterTag = (value, row) => {
  return row.categoryLabelName === value;
};
/** 写日记选中标签 */
function selectTag(tag) {
  form.value.categoryId = tag.id;
  selectedTag.value = tag;
}

// 暂未使用

/** 更多按钮操作 */
function handleCommand(command, row) {
  switch (command) {
    case "edit":
      console.log("Edit:", row);
      break;
    case "detail":
      console.log("Detail:", row);
      break;
    case "attachment":
      console.log("Attachment:", row);
      break;
    case "export":
      console.log("Export:", row);
      break;
    case "delete":
      console.log("Delete:", row);
      break;
    default:
      break;
  }
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "diary/diary/export",
    {
      ...queryParams.value
    },
    `diary_${new Date().getTime()}.xlsx`
  );
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getDiary(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改日记管理";
  });
}

getList();
getAllCategoryTagList();
getAllMoodWeatherList();
</script>

<style scope>
/* 查询---心情天气图标 */
.query-svg-icon {
  display: inline-block;
  vertical-align: middle;
  height: 25px;
}
/* 表格---内容预览 */
.text-overflow-ellipsis {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出文本 */
  text-overflow: ellipsis; /* 使用省略号表示被隐藏的文本 */
  max-width: 100%; /* 确保元素宽度适应父容器 */
}
/* 表格---内容预览对话框 */
.el-popover.el-popper {
  padding: 6px 15px;
  line-height: 2;
  text-indent: 2em;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  overflow: hidden;
}
.no-border-select .el-input__wrapper {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}
.no-border-select .el-input__wrapper.is-focus {
  --el-select-input-focus-border-color: none;
}
.el-tag {
  margin-right: 10px;
}
.el-tag.is-closable .el-tag__close {
  color: var(--tag-close-color);
}
/* 写日记---标题 */
.title-input {
  margin-top: 0px !important;
  height: 60px;
  width: 100%;
  border-bottom: 1px solid #f1f3f6;
}
.title-input .el-input__inner {
  text-align: center;
  font-weight: 450;
  font-size: 20px;
}
.title-input .el-input__wrapper {
  box-shadow: none;
}
.el-input.is-disabled {
  cursor: not-allowed;
  --el-disabled-bg-color: #fff;
  --el-disabled-text-color: #606266;
}
:root {
  --el-border-color-light: #fff;
}
/* 写日记---对话框 */
.el-dialog:not(.is-fullscreen) {
  margin-top: 1vh !important;
}
.info-row {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
}
.auto-area {
  display: flex;
  align-items: center;
  color: #a8abb2;
}
.location {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20px;
}
.function-area {
  display: flex;
  align-items: center;
}
/* 写日记---心情天气图标 */
.write-svg-icon {
  display: inline-block;
  vertical-align: middle;
  height: 25px;
}
/* 日记---标签 */
.el-popper .el-tag__content {
  margin-left: -28px;
}
/* 写日记---顶部退出按钮 */
.el-dialog__headerbtn .el-dialog__close {
  z-index: 1;
  columns: #606266;
  font-size: 18px;
}
/* 写日记---工具栏配置 */
.ql-toolbar.ql-snow {
  border: none;
  margin-top: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
  height: 35px;
  padding: 6px;
  margin-bottom: 15px;
}
/* 写日记---文本输入栏 */
.ql-container.ql-snow {
  border-radius: 8px;
  border: none;
  background-color: #f9fafb;
}
.ql-editor.ql-blank::before {
  color: #a8abb2;
  font-style: normal;
  font-size: 15px;
}
.editor p,
.editor ol,
.editor ul {
  font-size: 15px;
}
.el-dialog__body {
  padding: 30px 20px 10px 20px;
}
/* 写日记---字数统计 */
.icon-word-count {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: -20px;
  padding: 0 15px;
}
.icon-container {
  flex: 1;
  display: flex;
  justify-content: center;
}
.up-down-arrow {
  margin: 0;
}
.word-count {
  margin-left: auto;
  z-index: 1;
  font-size: 12px;
  color: #a8abb2;
}
/* 写日记---图片上传 */
.image-upload-area {
  margin-top: 15px;
  background-color: #f9fafb;
  padding: 12px 15px;
  border-radius: 8px;
}
.image-upload-title {
  font-size: 13px;
  color: #a8abb2;
}
.image-upload {
  margin-top: 10px;
}
.el-upload--picture-card {
  --el-upload-picture-card-size: 100px;
  background-color: #ffffff;
}
.el-upload-list--picture-card {
  --el-upload-list-picture-card-size: 100px;
}
.el-upload-list__item .el-icon--close-tip {
  font-size: 0px;
}
.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  object-fit: cover; /* 图片填充模式 */
}
/* 写日记---尾部 */
.el-dialog__footer {
  padding: 5px 20px 15px 20px;
}
.el-link__inner {
  font-size: 12px;
  margin-left: 5px;
}
</style>

